<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\tool\account\Account;
use think\model\relation\BelongsTo;

/**
 * 视频评论
 * Class Video
 * @package app\common\model
 */
class UserVideoComment extends Base
{
    protected $name = 'user_video_comment';

    public function video(): BelongsTo
    {
        return $this->belongsTo(BusinessVideo::class, 'video_id', 'id')->field('id,introduce,cover,link');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'uid', 'id')->field('id,nickname,photo,mobile,level_video_id');
    }

    public function getVideoLinkUrlAttr($value, $data): string
    {
        $link = BusinessVideo::where('id', $data['video_id'])->value('link');
        return $link ? $config = config('qiniu')['domain'].$link : '';
    }

    public static function add($param, $uid): array
    {
        parent::startTrans();
        try {
            parent::create([
                'uid' => $uid,
                'video_id' => $param['id'],
                'comment' => $param['comment'],
                'video_second' => $param['video_second'],
                'business_id' => BusinessVideo::where('id', $param['id'])->value('business_id')
            ]);
            BusinessVideo::where('id',$param['id'])->inc('total_comment')->update();
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function del(string $ids, int $business_id) :array
    {
        try{
            if(!$ids) return ['code' => -1, 'msg' => '请选择要删除的评论'];
            $business = UserVideoComment::whereIn('id',$ids)->column('distinct business_id');
            if(count($business) > 1) return ['code' => -1, 'msg' => '所选评论错误'];
            if($business_id != $business[0]) return ['code' => -1, 'msg' => '没有权限'];

            $count = count(explode(',', $ids));
            $counted = UserVideoComment::where(['business_id'=>$business_id, 'is_del'=>1])->whereMonth('delete_time')->count();
            $limit = Config::where('name', 'video_comment_del_count')->value('value');
            $paycount = $count + $counted - $limit;
            if($paycount > 0){
                $fee = Config::where('name', 'video_comment_del_fee')->value('value');
                $amount = round($fee * $paycount);
                $data = [
                    'ids'=>$ids,
                    'amount'=>$amount,
                    'title'=>'充值',
                    "url"=>"/business/VideoComment/pay?ids={$ids}&amount={$amount}&business_id={$business_id}",
                    'method' => getPaymentMethod('chain_bean,love_bean')
                ];
                return ['code' => 301, 'msg' => '请先充值', 'data'=>$data];

            }
            self::deleted($ids);
            return ['code' => 1, 'msg' => '操作成功'];

        }catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    public static function deleted(string $ids)
    {
        UserVideoComment::whereIn('id', $ids)->update(['is_del'=>1,'delete_time'=>date("Y-m-d H:i:s")]);

        foreach (explode(',', $ids) as $id){
            BusinessVideo::where('id',UserVideoComment::where('id', $id)->value('video_id'))->dec('total_comment')->update();
        }

        return true;
    }

    public static function payment($param, $user): array
    {
        try {
            $info = OrderVideoCommentDel::create([
                'sn' => date('Ymd') . $user->id . time(),
                'uid' => $user->id,
                'business_id' => $user->business_id,
                'pay_way' => $param['pay_way'],
                'total_amount' => $param['amount'],
                'real_amount' => $param['amount'],
                'comment_ids' => $param['ids']
            ]);
            $account = $param['pay_way'];
            switch ($account) {
                case "alipay":
                case "wechat":
                    return ['code' => -1, 'msg' => '暂不支持'];
                case "chain_bean":
                case "love_bean":
                    if (md5($param['pay_password']) != $user->pay_password) {
                        return ['code' => -1, 'msg' => '支付密码错误'];
                    }
                    if ($user->assets->$account < $info->real_amount) {
                        return ['code' => -1, 'msg' => '余额不足'];
                    }
                    return self::operations($info, $user, $account);
                default :
                    return ['code' => -1, 'msg' => '不支持的支付方式'];
            }

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function operations($info, $user, $account)
    {
        parent::startTrans();
        try {
            if (!in_array($account, ['wechat', 'alipay'])) {
                Account::getInstance()->basics($user->id, $account, $info->real_amount, '购买删除视频评论', '-')
                    ->createNormal($info->id);
            }
            $info->pay_state = 1;
            $info->pay_time = time();
            $info->save();

            self::deleted($info['comment_ids']);

            parent::commit();
            return ['code' => 1, 'msg' => '支付成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
